<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>Title</title>
    <link rel="stylesheet" href="../libs/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="../stylesheets/common.css">
    <style>
        label.error{
            color: red;
        }
        .error:not(label){
            border-color: red;
        }
    </style>
</head>
<body>

<nav class="navbar navbar-expand-sm navbar-dark bg-primary">
    <a class="navbar-brand" href="#">
        <img width="30" src="../images/wbb.jpeg" alt="">
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="../index.html">首页</a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="./posts.html">文章</a>
            </li>
            <li class="nav-item ">
                <a class="nav-link" href="../about.html">关于我们</a>
            </li>
        </ul>
    </div>
</nav>
<section class="content">
    <aside class="bg-info">
        <a class="nav-link text-light" href="../index.html">首页</a>
        <a class="nav-link text-danger" href="./posts.html">文章</a>
        <a class="nav-link text-light" href="../about.html">关于我们</a>
    </aside>
    <main>
        <div class="d-flex justify-content-between align-items-center">
            <h1>修改文章</h1>
        </div>
        <form class="form-block needs-validation " novalidate="novalidate">
            <div class="form-group">
                <label for="title">标题</label>
                <input  name="title" type="text" class="form-control" id="title">
            </div>
            <div class="form-group">
                <label for="description">描述</label>
                <input name="description" type="text" class="form-control" id="description">
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="poster">海报：</label>
                    <input name="poster" type="text" class="form-control row-cols-md-6" id="poster"placeholder="请输入地址">
                </div>
                <div class="form-group col-md-3">
                    <label for="author">发布者：</label>
                    <input name="author" type="text" class="form-control" id="author">
                </div>
                <div class="form-group col-md-3">
                    <label for="type">类型：</label>
                    <select name="type"class="form-control" id="type">
                        <option value="">请选择新闻类型</option>
                    </select>
                </div>
            </div>
            <div id="div1"></div>
            <button type="submit" class="btn btn-primary">修改</button>
        </form>

    </main>
</section>
<script src="../js/jquery-3.5.1.js"></script>
<script src="../libs/bootstrap/js/bootstrap.bundle.js"></script>
<script src="../js/posts/wangEditor.min.js"></script>
<script src="../js/jquery.validate.js"></script>
<script src="../js/messages_zh.js"></script>
<script>
    $(function () {
        $.ajax({
            url: "http://120.27.209.174:1010/api/v1/posts_type",
            success(res) {
                res.forEach(function(item) {
                    $(`<option value="${item.type}">${item.text}</option>`).appendTo("#type")
                })
            }
        })
        //序列化
        function serializeObject(form) {
            let o = {};
            let a = $(form).serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        }
        function searchParse(){
            var resultObj = {};
            var search = window.location.search;
            if(search && search.length > 1){
                var search = search.substring(1);
                var items = search.split('&');
                for(var index = 0 ; index < items.length ; index++ ){
                    if(! items[index]){
                        continue;
                    }
                    var kv = items[index].split('=');
                    resultObj[kv[0]] = typeof kv[1] === "undefined" ? "":kv[1];
                }
            }
            return resultObj;
        }
        const query = searchParse()
        const E = window.wangEditor
        const editor = new E("#div1")
        editor.config.height = 220
        editor.config.uploadImgShowBase64 = true
        editor.create()

        //数据回填
        $.ajax({
            url: `http://120.27.209.174:1010/api/v1/posts/${query.id}`,
            success(res) {
                $("[name=title]").val(res.title)
                $("[name=description]").val(res.description)
                $("[name=poster]").val(res.poster)
                $("[name=author]").val(res.author)
                $("[name=type]").val(res.type)
                editor.txt.html(res.detail)
                console.log(res)
            }
        })
        //表单验证
        $(".needs-validation").validate({
            //debug: true, //调试模式取消submit的默认提交功能
            //errorClass: "label.error", //默认为错误的样式类为：error
            focusInvalid: false, //当为false时，验证无效时，没有焦点响应
            onkeyup: false,
            submitHandler: function(form){   //表单提交句柄,为一回调函数，带一个参数：form
                // 序列化之后的数据
                const data = serializeObject(form)
                data.detail = editor.txt.html()
                console.log(data.poster)
                $.ajax({
                    method: "PUT",
                    url: `http://120.27.209.174:1010/api/v1/posts/${query.id}`,
                    data: data,
                    success(res) {
                        location.href = `./posts.html?id=${query.id}`
                    }
                })
            },
            rules:{
                title: {required:true, rangelength:[ 10, 30]},
                description: {required:true},
                poster: {required:true, url: true},
                author: {required:true},
                type: {required:true},
                detail: {required:true},
            },
            messages:{
                type:"必选"
            }
        })
    })
</script>
</body>
</html>